<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="listQuery.orderNo" placeholder="订单号" style="width: 200px;" class="filter-item" @keyup.enter.native="searchList" />
      <el-input v-model="listQuery.phone" placeholder="手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="searchList" />
      <el-select v-model="listQuery.state" placeholder="订单状态" clearable class="filter-item" style="width: 150px" @change="searchList">
        <el-option v-for="item in stateOptions" :key="item.index" :label="item.value" :value="item.index" />
      </el-select>
      <el-select v-model="listQuery.suppliergid" filterable placeholder="选择供货商" style="width: 150px;" class="filter-item" clearable>
        <el-option
          v-for="item in suppliergidOptions"
          :key="item.gid"
          :label="item.name"
          :value="item.gid"
        />
      </el-select>
      <el-date-picker
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="searchList">
        搜索
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="订单号" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" width="100px" align="center">
        <template slot-scope="{row}">
          <span>¥{{ row.totalPrice.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" width="100px" align="center">
        <template slot-scope="{row}">
          <span>¥{{ row.payMoney.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货电话" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" align="center">
        <template slot-scope="{row}">
          <span>{{ `${row.city} ${row.address}` }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.state | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流信息" align="center">
        <template slot-scope="{row}">
          <span>{{ row.state==2?`${row.courier} ${row.courierNo}`:`----` }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center">
        <template slot-scope="{row}">
          <span>{{ renderTime(row.payTime) || '----' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="发货时间" align="center">
        <template slot-scope="{row}">
          <span>{{ renderTime(row.deliverTime) || '----' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ renderTime(row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200px">
        <template slot-scope="{row}">
          <el-button-group>
            <el-button v-if="row.state==1" type="primary" size="mini" @click="edit(row)">
              发货
            </el-button>
            <el-button size="mini" type="success" @click="detailHander(row.gid)">
              详情
            </el-button>
            <el-button v-if="row.state>=0" type="default" size="mini" @click="cancel(row)">
              取消
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :limit.sync="listQuery.pagesize"
      :page.sync="listQuery.page"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;" @keyup.enter.native="updateOrderDetail">
        <el-form-item label="订单号">
          <span>{{ temp.orderNo }}</span>
        </el-form-item>
        <el-form-item label="快递公司" prop="courier">
          <el-input v-model="temp.courier" />
        </el-form-item>
        <el-form-item label="快递单号" prop="courierNo">
          <el-input v-model="temp.courierNo" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateOrderDetail()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <Dialog v-model="show" :gid="gid" />
  </div>
</template>

<script>
import { getOrders, updateDeliverWare, cancel } from '@/api/orders'
import Dialog from './components/dialog'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getSupplier } from '@/api/supplier'

import { renderTime } from '@/utils/util'
// -3.已退款 -2.已过期 -1.已取消 0.未付款 1.待发货 2.待收货 3.已收货 4.售后
const stateOptions = [
  { index: undefined, value: '全部' },
  { index: -3, value: '已退款' },
  { index: -2, value: '已过期' },
  { index: -1, value: '已取消' },
  { index: 0, value: '未付款' },
  { index: 1, value: '待发货' },
  { index: 2, value: '待收货' },
  { index: 3, value: '已收货' },
  { index: 4, value: '售后' }
]
const calendarTypeKeyValue = stateOptions.reduce((acc, cur) => {
  acc[cur.index] = cur.value
  return acc
}, {})
export default {
  name: 'Orders',
  components: { Pagination, Dialog },
  directives: { waves },
  filters: {
    typeFilter(index) {
      return calendarTypeKeyValue[index]
    }
  },
  data() {
    return {
      gid: '', // 订单的gid，传值给组件
      show: false,
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        orderNo: '',
        suppliergid: '',
        phone: '',
        state: '',
        page: 1,
        pagesize: 10,
        startTime: '',
        endTime: ''
      },
      suppliergidOptions: [],
      date: '',
      stateOptions,
      state: '',
      temp: {
        gid: '',
        orderNo: '',
        courier: '',
        courierNo: ''
      },
      rules: {
        courier: [{ required: true, message: '请输入快递公司', trigger: 'blur' }],
        courierNo: [{ required: true, message: '请输入请输入快递号', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '发货',
        create: 'Create'
      },
      detailDialog: false,
      detailForm: {
        gid: '',
        orderNo: '',
        courier: '',
        courierNo: ''
      },
      waresLodding: true
    }
  },
  watch: {
    date: {
      handler: function(newV) {
        if (newV && newV.length === 2) {
          this.listQuery.startTime = this.renderTime(newV[0], '{y}-{m}-{d}')
          this.listQuery.endTime = this.renderTime(newV[1] + 86400000, '{y}-{m}-{d}')
        } else if (newV && newV.length !== 2) {
          this.$message({
            type: 'error',
            message: '日期选择出错'
          })
        } else {
          this.listQuery.startTime = ''
          this.listQuery.endTime = ''
        }
      }
    }
  },
  created() {
    this.getList()
    this.getSupplier()
  },
  methods: {
    renderTime,
    detailHander(gid) {
      this.gid = ''
      this.gid = gid
      this.show = true
    },
    getSupplier() {
      getSupplier().then(res => {
        this.suppliergidOptions = res.result.list
      })
    },
    // 1：域名 2：邮箱 3：网站4：安全
    getList() {
      this.listLoading = true
      getOrders(this.listQuery).then(response => {
        this.list = response.result.list
        this.total = response.result.total
        this.listLoading = false
      })
    },
    searchList() {
      this.listQuery.page = 1
      this.getList()
    },
    edit(row) {
      this.temp.gid = row.gid
      this.temp.orderNo = row.orderNo
      this.temp.courier = row.courier
      this.temp.courierNo = row.courierNo
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    cancel(row) {
      this.$confirm('确定取消该订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancel({ gid: row.gid }).then(res => {
          this.$message.success(res.message)
          this.getList()
        })
      })
    },
    // 更新表格内容
    updateOrderDetail() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateDeliverWare({ gid: this.temp.gid, orderNo: this.temp.orderNo, courier: this.temp.courier, courierNo: this.temp.courierNo }).then(() => {
            this.$notify({
              title: '成功',
              message: '发货成功~',
              type: 'success',
              duration: 2000
            })
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    }

  }

}
</script>
<style lang="scss">
    @import '@/assets/scss/mixin.scss';
    // .el-form-item--medium{
    //   .el-form-item__content{
    //     display: flex;
    //     align-items: center;
    //     .el-input{
    //       &+.el-button{
    //         margin-left: 0.625rem;
    //       }
    //     }
    //     .el-button{
    //       &:not(:first-child){
    //         margin-left: 0.625rem;
    //       }
    //     }
    //   }
    // }
    .detail{
      .el-form--inline{
         .el-form-item{
           width: 23%;
           .el-table{
             thead{
               tr{
                 th{
                   line-height: 23px;
                 }
               }
             }
           }
         }
      }
    }
</style>
